package com.chenjiagou.controller;

import com.chenjiagou.pojo.User;
import com.chenjiagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/user")

public class UserController {

    @Autowired
    private UserService userService;



    @GetMapping("/list")
    public String listUsers(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(required = false) String keyword,
                            Model model) {
        int pageSize = 10;
        int offset = (page - 1) * pageSize;

        List<User> allUsers = userService.getAllUsers();

        if (keyword != null && !keyword.isEmpty()) {
            allUsers = allUsers.stream()
                    .filter(user -> user.getUsername() != null && user.getUsername().contains(keyword))
                    .collect(Collectors.toList());
        }


        int totalItems = allUsers.size();
        List<User> paginatedUsers = allUsers.stream()
                .skip(offset)
                .limit(pageSize)
                .collect(Collectors.toList());

        model.addAttribute("users", paginatedUsers);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", (int) Math.ceil((double) totalItems / pageSize));
        model.addAttribute("startNo", offset);
        model.addAttribute("keyword", keyword); // 用于回显搜索内容
        return "userlist";
    }

    // 删除用户
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable int id) {
        userService.deleteUserById(id);
        return "redirect:/user/list";
    }

    @PostMapping("/update")
    public String updateUser(
            @RequestParam int id,
            @RequestParam String username,
            @RequestParam String phone,
            @RequestParam String email,
            @RequestParam int role,
            @RequestParam int status) {

        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPhone(phone);
        user.setEmail(email);
        user.setRole(role);
        user.setStatus(status);

        userService.updateUser(user);

        return "redirect:/user/list";
    }



}
